package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.util.StringUtil;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.framework.config.IotClientConfig;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备表Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient iotClient;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备表列表
     *
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }
    /**
     * 导出设备表列表
     */
    @Override
    public void sycProductList() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(20);
        ListProductsResponse response = iotClient.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("同步产品列表失败");
        }
        List<ProductSummary> products = response.getProducts();
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(products));
    }
    /**
     * 查询所有产品列表
     */
    @Override
    public List<ProductVo> getAllProduct() {
        String products = (String) redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST);
        if (StringUtil.isEmpty(products)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(products, ProductVo.class);
    }
    /**
     * 注册设备
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        // 判断设备名称是否存在
        long count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if (count > 0) {
            throw new BaseException("设备名称已存在");
        }
        // 判断设备标识是否存在
        count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()));
        if (count > 0) {
            throw new BaseException("设备标识码已存在");
        }
        // 判断同一位置是否绑定了相同的产品
        count = this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(deviceDto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
        );
        if (count > 0) {
            throw new BaseException("该设备已存在");
        }
        // 注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setDeviceName(deviceDto.getDeviceName());
        body.setNodeId(deviceDto.getNodeId());
        body.setProductId(deviceDto.getProductKey());
        // 秘钥设置
        AuthInfo authInfo = new AuthInfo();
        String secert = UUID.randomUUID().toString().replace("-", "");
        authInfo.setSecret(secert);

        body.setAuthInfo(authInfo);
        request.setBody(body);
        AddDeviceResponse response = iotClient.addDevice(request);
        if (response.getHttpStatusCode() != 201) {
            throw new BaseException("设备注册失败");
        }
        // 本地保存设备
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setBindingLocation(String.valueOf(deviceDto.getBindingLocation()));
        device.setIotId(response.getDeviceId());
        device.setSecret(secert);
        this.save(device);
    }
    /**
     * 获取设备详细信息
     * @param iotId
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        // 查询本地设备数据
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }
        // 调用华为云接口查询设备详情
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = iotClient.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("设备详情查询失败");
        }
        String status = response.getStatus();
        String activeTime = response.getActiveTime();
        // 属性拷贝
        DeviceDetailVo bean = BeanUtil.toBean(device, DeviceDetailVo.class);
        bean.setDeviceStatus(status);
        bean.setBindingLocation(Long.valueOf(device.getBindingLocation()));
        // 日期转换
        if (StringUtil.isNotEmpty(activeTime)) {
            LocalDateTime localDateTime = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
            localDateTime = DateTimeZoneConverter.utcToShanghai(localDateTime);
            bean.setActiveTime(localDateTime);
        }
        return bean;
    }
    /**
     * 查询设备上报数据
     * @param iotId
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = iotClient.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("查询设备属性失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            List<Object> emptyList = Collections.emptyList();
            return AjaxResult.success(emptyList);
        }
        DeviceShadowProperties reported = shadow.get(0).getReported();
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());
        List<Map<String, Object>> list = new ArrayList<>();
        String eventTimeStr = reported.getEventTime();
        LocalDateTime time = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(time);
        jsonObject.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", eventTime);
            list.add(map);
        });
        return AjaxResult.success(list);
    }
    /**
     * 修改设备信息
     * @param deviceDto
     */
    @Override
    public void updateDevice(DeviceDto deviceDto) {
        Device device = this.getById(deviceDto.getId());
        if(ObjectUtil.isEmpty(device)){
            throw new BaseException("设备不存在");
        }
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(deviceDto.getDeviceName());
        AuthInfoWithoutSecret secert = new AuthInfoWithoutSecret();
        secert.setSecureAccess(true);
        body.setAuthInfo(secert);
        request.setBody(body);
        UpdateDeviceResponse response = iotClient.updateDevice(request);
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("设备更新失败");
        }

        long count = this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(deviceDto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .ne(Device::getId, device.getId())
        );
        if(count > 0){
            throw new BaseException("该设备已存在");
        }
        BeanUtil.copyProperties(deviceDto, device);
        if(device.getLocationType() == 0){
            UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", device.getId())
                    .set("physical_location_type", null)
                    .set("device_description", null);
            this.update(updateWrapper);
        }
        device.setBindingLocation(String.valueOf(deviceDto.getBindingLocation()));
        device.setDeviceName(deviceDto.getDeviceName());
        this.updateById(device);
    }
    /**
     * 删除设备
     * @param iotId
     */
    @Override
    public void deleteById(String iotId) {
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        iotClient.deleteDevice(request);
        Long id = device.getId();
        this.removeById(id);
    }
    /**
     * 查询产品详情
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        if(StringUtil.isEmpty(productKey)){
            throw new BaseException("产品Key不能为空");
        }
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = iotClient.showProduct(request);
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("产品详情查询失败");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollUtil.isEmpty(serviceCapabilities)){
            return AjaxResult.success(Collections.emptyList());
        }
        return AjaxResult.success(serviceCapabilities);
    }
}
